import { computed, ref } from "vue";
import { defineStore } from "pinia";
import { ElMessage } from "element-plus";
import { getUserPlayListAllAPi, getSongUrlAPi } from "@/apis/song.js";

export const useAudioStore = defineStore("audio", () => {
  // 获取 audio 标签的元素
  const audioRef = ref(null);
  const getAudio = (audio) => {
    audioRef.value = audio.value;
  };

  // 获取歌单内所有歌曲列表
  const allSongList = ref([]);
  const privileges = ref([]);
  const getAllPlayList = async (id, limit, offset) => {
    const { data } = await getUserPlayListAllAPi(id, limit, offset);
    allSongList.value = data.songs;
    privileges.value = data.privileges;
  };

  // 播放的歌单
  const activeSongList = ref([]);

  // 当前正在播放歌曲的 index
  const playIndex = ref(0);
  // 计算歌曲播放的索引，当新值大于列表的数量时，使索引变为 0（播放第一首）
  // 当新值小于 0 时，使索引变为列表的长度（播放最后一首）
  const activeIndex = computed({
    set(newVal) {
      if (newVal > activeSongList.value.length - 1) {
        playIndex.value = 0;
      } else if (newVal < 0) {
        playIndex.value = activeSongList.value.length - 1;
      } else {
        playIndex.value = newVal;
      }
    },
    get() {
      return playIndex.value;
    },
  });
  // 当前正在播放歌曲的信息
  const playSongInfo = ref({});

  // 歌曲音质等级,默认“较高”
  const songLevel = ref("higher");

  // 获取准备播放的歌曲的 url
  const songResult = ref({});
  const getSongUrl = async (song, index) => {
    playIndex.value = index;
    playSongInfo.value = song;
    const { data } = await getSongUrlAPi(song.id, songLevel.value);
    const songResultData = data.data[0];
    if (data.code !== 200)
      return ElMessage.warning("获取播放地址出错，请切换歌曲");
    // vip 歌曲，试听 30 秒
    if (songResultData.freeTrialPrivilege.cannotListenReason !== null)
      ElMessage("试听 30 秒");
    songResult.value = songResultData;
    // 检查是否有该歌曲的资源，没有，则播放下一首
    if (songResult.value.code === 404) {
      nextSong();
      ElMessage("没有歌曲资源，已自动跳过");
    }
  };

  // 根据音质获取歌曲 Url
  const getLevelSongUrl = async () => {
    const { data } = await getSongUrlAPi(
      playSongInfo.value.id,
      songLevel.value
    );
    songResult.value = data.data[0];
  };

  // 歌曲的总时长
  const totalDuration = ref(0);
  // 进度条每次前进累加的百分比
  const sliderTime = ref(0);

  // 歌曲的播放状态
  const playStaus = ref(false);
  // 侦听歌曲播放
  const listenerPlay = () => {
    audioRef.value.addEventListener("play", function () {
      playStaus.value = true;
    });
  };

  // 侦听歌曲暂停
  const listenerPause = () => {
    audioRef.value.addEventListener("pause", function () {
      playStaus.value = false;
    });
  };

  // 侦听歌曲可以正常播放且无需停顿时执行
  const listenerCanplaythrough = () => {
    audioRef.value.addEventListener("canplaythrough", function () {
      totalDuration.value = this.duration;
      console.log("可以播放");
    });
  };

  // 侦听歌曲结束
  const listenerEnded = () => {
    audioRef.value.addEventListener("ended", function () {
      nextSong();
    });
  };

  // 下一曲
  const nextSong = () => {
    playSong(activeIndex.value++);
  };

  // 上一曲
  const frontSong = () => {
    playSong(activeIndex.value--);
  };

  // 播放
  const playSong = (setSong) => {
    if (!activeSongList.value.length) {
      return ElMessage({
        message: "请选择播放列表",
        grouping: true,
        type: "warning",
      });
    }
    setSong;
    getSongUrl(activeSongList.value[activeIndex.value], activeIndex.value);
  };

  // 当前的播放进度
  const currentTime = ref(0);

  // 侦听歌曲播放进度
  // 节流函数
  let timer = true;
  const listenerTimeUpdate = (rollingLyricFn = () => {}) => {
    audioRef.value.addEventListener("timeupdate", function () {
      currentTime.value = this.currentTime;
      if (timer) {
        timer = setTimeout(() => {
          timer = true;
          sliderTime.value = (this.currentTime / totalDuration.value) * 100;
        }, 1000);
      }
      rollingLyricFn();
      timer = false;
    });
  };

  return {
    audioRef,
    allSongList,
    privileges,
    activeSongList,
    playSongInfo,
    songLevel,
    songResult,
    playStaus,
    playIndex,
    activeIndex,
    currentTime,
    totalDuration,
    sliderTime,
    getAudio,
    listenerPlay,
    listenerPause,
    listenerEnded,
    listenerCanplaythrough,
    listenerTimeUpdate,
    getAllPlayList,
    getSongUrl,
    getLevelSongUrl,
    nextSong,
    frontSong,
    playSong,
  };
});
